package com.lemon.smartsafety.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.safecloud.greendao.PlayView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.bind.BindVo;
import com.lemon.smartsafety.entity.common.CommonVo;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.main.MainAdEvent;
import com.lemon.smartsafety.entity.event.main.MainNewsColumnEvent;
import com.lemon.smartsafety.entity.event.main.MainPanelButtonEvent;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerClickEventForMain;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerOpenEvent;
import com.lemon.smartsafety.entity.event.user.LoginOutEvent;
import com.lemon.smartsafety.entity.main.MainPanelButton;
import com.lemon.smartsafety.entity.main.MainRcvItemBase;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.entity.version.VersionVo;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.MainFragmentServices;
import com.lemon.smartsafety.http.service.NewsInfoServices;
import com.lemon.smartsafety.http.service.UpdateServices;
import com.lemon.smartsafety.http.service.UserServices;
import com.lemon.smartsafety.rayeye.entity.AllCount;
import com.lemon.smartsafety.rayeye.util.Urls;
import com.lemon.smartsafety.result.OldBaseMode;
import com.lemon.smartsafety.result.fire.FireGovBindMode;
import com.lemon.smartsafety.ui.activity.address.AddressBookMainActivity;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafety.ui.activity.fire.FirefightingMainActivity;
import com.lemon.smartsafety.ui.activity.nine.NineSmallPropActivity;
import com.lemon.smartsafety.ui.activity.notice.NoticeListActivity;
import com.lemon.smartsafety.ui.activity.safe.inspection.SafeInspectionPanelActivity;
import com.lemon.smartsafety.ui.activity.safe.worker.PanelActivity;
import com.lemon.smartsafety.ui.activity.user.LoginActivity;
import com.lemon.smartsafety.ui.adapter.common.RcvViewType;
import com.lemon.smartsafety.ui.adapter.main.MainFragmentAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.ToolbarSwipeRefreshFragment;
import com.lemon.smartsafety.update.UpdateManager;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.app.UserTypeHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.Convertor;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.orhanobut.logger.Logger;
import com.thefinestartist.finestwebview.FinestWebView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Cooliean on 16/1/16.
 */
public class MainFragment extends ToolbarSwipeRefreshFragment {
    //    private MainAdapter mMainAdapter;

    private MainFragmentAdapter mMainAdapter;


    public static final int AD_POSITION          = 0;
    public static final int OPTION_POSITION      = 1;
    public static final int NEWS_COLUMN_POSITION = 3;

    private List<MainRcvItemBase> mItems = new ArrayList<MainRcvItemBase>();


    private List<MainPanelButton> mMainButtons = DataUtil.getMainUIButtons();

    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;


    private String mRayEyeCountUrl = "";


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRayEyeCountUrl = String.format(Urls.ALL_COUNT_URL, mSharedPreferencesHelper.getRayEyeUrl());
        initializedView();
    }


    /**
     * 通过网络初始化视图
     */
    private void initializedView() {
        checkPermission(getString(R.string.permission_network_tip), new LemonPermissionListener() {
            @Override
            public void onPermissionGranted(int requestCode) {
                //获取图片新闻
                getMainAD();
                getRayEye();
            }

            @Override
            public void onPermissionDenied(int requestCode,ArrayList<String> deniedPermissions) {
                mHUDUtil.showErrorTip(getString(R.string.permission_denied_action));
            }
        }, Manifest.permission.INTERNET);


        new Handler().postAtTime(new Runnable() {
            @Override
            public void run() {
                //版本升级
                getVersionInfo();
            }
        }, 1000);


        if (!mSharedPreferencesHelper.isLogin()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    handlerNoticeCount(0);
                }
            }, 500);
        } else {
            getUnReadNoticeCount();
        }
    }

    public static MainFragment newInstance() {
        MainFragment mainFragment = new MainFragment();
        return mainFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_main;
    }

    @Override
    protected int getTitle() {
        return R.string.app_name;
    }

    @Override
    protected void initViews() {
        super.initViews();

        setAdapter();

    }

    public void setAdapter() {
        mItems.clear();
        mSwipeRefreshLayout.setBackgroundResource(R.color.md_grey_50);
        //这里是添加广告位置
        List<PlayView> playViews = new ArrayList<>();
        for (int i = 0; i < 1; i++) {
            PlayView playView = new PlayView(Convertor.toLong(i + ""), getString(R.string.app_name), "http://10.10.1.233/files/upload/E.jpg");
            playViews.add(playView);
        }
        MainRcvItemBase<List<PlayView>> itemAd = new MainRcvItemBase();
        itemAd.setViewType(RcvViewType.MainRcvViewType.TYPE_AD);
        itemAd.setData(playViews);
        mItems.add(itemAd);


        //这里添加主菜单了啦
        MainRcvItemBase<List<MainPanelButton>> itemOption = new MainRcvItemBase();
        itemOption.setViewType(RcvViewType.MainRcvViewType.TYPE_MAIN_OPTION);
        itemOption.setData(mMainButtons);
        mItems.add(itemOption);

        MainRcvItemBase head1 = new MainRcvItemBase();
        head1.setViewType(RcvViewType.MainRcvViewType.TYPE_SECTION_HEAD);
        mItems.add(head1);

        mMainAdapter = new MainFragmentAdapter(mItems);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setAdapter(mMainAdapter);

        mMainAdapter.notifyDataSetChanged();
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_login:
                //add by Andrew.yin 2017/6/28 begin. 修复当用户登录后，不退出的情况下，能再次登陆的问题。
                if (mSharedPreferencesHelper.isLogin()) {
                    DrawerOpenEvent openEvent = new DrawerOpenEvent();
                    openEvent.setEventResult(Constants.Result.SUCCESS);
                    AppService.getBus().post(openEvent);
                } else {
                    UIHelper.showLoginActivity(getActivity());
                }
                //add by Andrew.yin 2017/6/28 end
                break;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                stopRefreshing();
                initializedView();
            }
        });
    }

    /**
     * 升级用的地方，获取服务器的版本信息
     */
    public void getVersionInfo() {
        int versionCode = AppUtils.getVersionCode(IApplication.context());
        UpdateServices.init(IApplication.context()).getUpdateInfo(versionCode);
    }

    public void getMainAD() {
        MainFragmentServices.init(IApplication.context()).getMainPanelAd();
    }

    public void getNewsColumn() {
        NewsInfoServices.init().getNewsColumn();
    }

    public void getUnReadNoticeCount() {
        UserServices.init().getMyUnReadNoticeCount();
    }

    private void getRayEye() {
        MainFragmentServices.init().getBindInfo(ApplicationInfo.ApplicationCode.FIRE_SUPERVISON, EventTag.FIRE_SUPERVISON_MAIN);
    }


    @Override
    public void onResume() {
        super.onResume();
        UserServices.init().getMyUnReadNoticeCount();
    }

    /**
     * 主屏广告类型按钮事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MainAdEvent event) {
        if (EventTag.TAG_MAIN_PANEL_AD.equals(event.getTag())) {
            String url = new SharedPreferencesServer(IApplication.context()).getRequestUrl(UrlInfo.ARTICLE_DETAIL);
            url += "?rp=" + Constants.RP_PASSWORD + "&article_id=" + event.getPlayView().getId();

            new FinestWebView.Builder(getActivity()).theme(R.style.FinestWebViewTheme)
                                                    .titleDefault("公告新闻")
                                                    .showUrl(false)
                                                    .statusBarColorRes(R.color.colorPrimaryDark)
                                                    .toolbarColorRes(R.color.colorPrimary)
                                                    .titleColorRes(R.color.white)
                                                    .urlColorRes(R.color.colorPrimaryLight)
                                                    .iconDefaultColorRes(R.color.finestWhite)
                                                    .progressBarColorRes(R.color.finestWhite)
                                                    .showSwipeRefreshLayout(true)
                                                    .swipeRefreshColorRes(R.color.colorPrimaryDark)
                                                    .menuSelector(R.drawable.selector_light_theme)
                                                    .menuTextGravity(Gravity.CENTER)
                                                    .menuTextPaddingRightRes(R.dimen.defaultMenuTextPaddingLeft)
                                                    .dividerHeight(0)
                                                    .gradientDivider(false)
                                                    .setCustomAnimations(R.anim.slide_up, R.anim.hold, R.anim.hold, R.anim.slide_down)
                                                    .showMenuShareVia(false)
                                                    .stringResCopiedToClipboard(R.string.web_view_copied)
                                                    .stringResCopyLink(R.string.web_view_copy)
                                                    .stringResOpenWith(R.string.web_view_open)
                                                    .show(url);
        }
    }

    /**
     * 主屏按钮事件处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MainPanelButtonEvent event) {

        if (!EventTag.TAG_MAIN_PANEL_BUTTON_EVENT.equals(event.getTag())) {
            return;
        }
        if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.HIDDEN_DANGER) {
            if (AppService.getInstance().isLogin()) {
                MainFragmentServices.init().getBindInfo(event.getButton().getApplicationCode());
            } else {
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.FIRE_SAFE) {
            fireCheckAction();
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.ANJIAN_NOTICE) {
            if (AppService.getInstance().isLogin()) {
                Log.e("ANJIAN_NOTICE  DeBug",event.getButton().getApplicationCode().getCode());
                MainFragmentServices.init().getBindInfo(event.getButton().getApplicationCode());
            } else {
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.FIRE_ADDRESS) {
            if (AppService.getInstance().isLogin()) {
                UIHelper.showActivity(getActivity(), AddressBookMainActivity.class);
            } else {
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.JIFEN_SHOP) {
            if (AppService.getInstance().isLogin()) {
                mHUDUtil.showInfoTip("商城未开放");
//                UIHelper.showActivity(getActivity(), AddressBookMainActivity.class);
            } else {
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.USER_PROFILE) {
            if (mSharedPreferencesHelper.isLogin()) {
                DrawerOpenEvent openEvent = new DrawerOpenEvent();
                openEvent.setEventResult(Constants.Result.SUCCESS);
                AppService.getBus().post(openEvent);
            } else {
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.FIRE_SUPERVISON) {
            if (mSharedPreferencesHelper.isLogin()) {
                if (mSharedPreferencesHelper.getRayEyeUrl().length() == 0) {
                    mHUDUtil.showErrorTip("请重新登录后使用该功能");
                    return;
                } else {
                    //UIHelper.showActivity(getActivity(), BuildingListActivity.class);
                    //老的角色检验
                    MainFragmentServices.init().getBindInfo(ApplicationInfo.ApplicationCode.FIRE_SUPERVISON);
                }
            }else{
                UIHelper.showLoginActivity(getActivity());
            }
        } else if (event.getButton().getApplicationCode() == ApplicationInfo.ApplicationCode.NINE_SMALL) {
            if (mSharedPreferencesHelper.isLogin()) {
                if (UserTypeHelper.isDataCollection()) {//数据采集员无限使用该功能
                    UIHelper.showActivity(getActivity(), NineSmallPropActivity.class);
                } else {//机构用户不能使用安全巡查，其它直接进入安全巡查
                    if (UserTypeHelper.isGovUser()) {
                        mHUDUtil.showErrorTip("机构用户不能使用该功能");
                    } else {
                        mHUDUtil.showDoneTip("您已经登录，将跳转至安全巡查", new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {
                                fireCheckAction();
                            }
                        });
                    }
                }
            } else {//没有登录的直接使用该功能
                UIHelper.showActivity(getActivity(), NineSmallPropActivity.class);
            }

        }
    }


    /**
     * 安全巡查按钮事件
     */
    private void fireCheckAction() {
        if (AppService.getInstance().isLogin()) {
            if (UserTypeHelper.isDataCollection()) {
                UIHelper.showSafeDataCollectionMain(getActivity());
            } else if (UserTypeHelper.isSafer() || UserTypeHelper.isWorker()) {
                MainFragmentServices.init().getBindInfo(ApplicationInfo.ApplicationCode.FIRE_SAFE.getCode());
            } else {
                mHUDUtil.showDoneTip(R.string.city_cant_use);
            }
        } else {
            UIHelper.showLoginActivity(getActivity());
        }

    }

    /**
     * 主屏新闻类型按钮事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MainNewsColumnEvent event) {
        if (EventTag.TAG_MAIN_NEWS_COLUMN_EVENT.equals(event.getTag())) {
            DrawerClickEventForMain mainEvent = new DrawerClickEventForMain(R.string.draw_news);
            mainEvent.setEventResult(Constants.Result.SUCCESS);
            mainEvent.setDrawPosition(1);
            mainEvent.setColumnPosition(event.getIndex());
            AppService.getBus().post(mainEvent);
        }
    }

    /**
     * 登录成功后要获取未读公告
     *
     * @param event
     */

    @Subscribe
    public void onEventMainThread(AppEvent event) {
        if (LoginActivity.class.getName().equals(event.getTag())) {
            handlerNoticeCount(0);
            getUnReadNoticeCount();
        }
    }


    /**
     * 注销后未读清零
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(LoginOutEvent event) {
        handlerNoticeCount(0);
        handlerRayEyeCount(0);
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_MAIN_PANEL_AD.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {//为了保证位置顺序正确，所以在获取完广告后在获取新闻的类型
                getNewsColumn();
            }
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                List<PlayView> adItems = (List<PlayView>) event.getObj();
                if (adItems != null && adItems.size() != 0) {
                    MainRcvItemBase<List<PlayView>> itemAd = new MainRcvItemBase<>();
                    itemAd.setViewType(RcvViewType.MainRcvViewType.TYPE_AD);
                    itemAd.setData((List<PlayView>) event.getObj());
                    mItems.set(AD_POSITION, itemAd);
                    mMainAdapter.notifyItemChanged(AD_POSITION);
                }
            }
        } else if (EventTag.TAG_MAIN_NEWS_COLUMN_HTTP.equals(event.getTag())) {//获取新闻分类
          /*  if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                List<NewsColumn> colNews = (List<NewsColumn>) event.getObj();
                if (colNews != null && colNews.size() != 0) {
                    MainRcvItemBase<List<NewsColumn>> itemNews = new MainRcvItemBase<>();
                    itemNews.setViewType(RcvViewType.MainRcvViewType.TYPE_NEWS_COLUMN);
                    itemNews.setData((List<NewsColumn>) event.getObj());
                    if (mItems.size() == 4) {
                        mItems.set(NEWS_COLUMN_POSITION, itemNews);
                    } else {
                        mItems.add(itemNews);
                    }
                    mMainAdapter.notifyItemChanged(mItems.size() - 1);
                }
            }*/
        } else if (EventTag.TAG_BIND_INFO_HTTP.equals(event.getTag())) {//获取绑定信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    BindVo bindVo = (BindVo) event.getObj();
                    if (ApplicationInfo.ApplicationCode.FIRE_SUPERVISON.getCode().equals(event.getOther().toString())) {
                        httpGetFireBind( bindVo, event.getOther().toString());
                    }else {
                        handleBindInfo(mHUDUtil, getActivity(), bindVo, event.getOther().toString());
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_UPDATE_INFO.equals(event.getTag())) {//版本更新部分逻辑
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    VersionVo item = (VersionVo) event.getObj();
                    if (null != item) {
                        boolean isForce = item.isForce();
                        UpdateManager updateManager = new UpdateManager(item.getVersionRemark(), item.getDownloadUrl(), item
                                .getVersionName(), Constants.APP_DOWNLOAD_FILE_NAME, isForce, getActivity());
                        updateManager.checkUpdateInfo();
                    }
                } else {
                    //mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_MY_UN_READ_NOTICE.equals(event.getTag())) {//获取未读公告数字
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    CommonVo vo    = (CommonVo) event.getObj();
                    String   count = StringUtils.nullValue(vo.getName(), "0");
                    handlerNoticeCount(Convertor.toInt(count));
                }
            }


        } else if (EventTag.FIRE_SUPERVISON_MAIN.equals(event.getTag())) {//为了获取物联网的东西要先获取一次这个绑定信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    BindVo bindVo = (BindVo) event.getObj();
                    if (StringUtils.nullValue(bindVo.getBindCode()).length() != 0) {
                        getRayEyeCount(bindVo.getBindCode());
                    } else {
                        handlerRayEyeCount(0);
                    }
                }else{
                    handlerRayEyeCount(0);
                }
            }
        }
    }


    private void handlerNoticeCount(int count) {
        DataUtil.getMainButtonByResString(mMainButtons, R.string.app_option_3).setBadgeCount(count);
        mMainAdapter.notifyDataSetChanged();
    }

    private void handlerRayEyeCount(int count) {
        Logger.i(""+count);
        DataUtil.getMainButtonByResString(mMainButtons, R.string.app_option_7).setBadgeCount(count);
        mMainAdapter.notifyDataSetChanged();
    }

    private void getRayEyeCount(String code) {
        if (mSharedPreferencesHelper.getRayEyeUrl().length() == 0) {
            return;
        }
        LemonRequestParams params = new LemonRequestParams();
        params.put("code", code);
        params.put("key", Urls.APP_FIRE_SUPERVISON_KEY);
        OkHttpUtils.post()
                   .url(mRayEyeCountUrl)
                   .tag(mRayEyeCountUrl)
                   .params(params)
                   .build()
                   .execute(new Callback<AllCount>() {
                       @Override
                       public AllCount parseNetworkResponse(Response response) throws Exception {
                           return new Gson().fromJson(response.body().string(), getType());
                       }

                       @Override
                       public void onError(Call call, Exception e) {

                       }

                       @Override
                       public void onResponse(AllCount response) {
                           if (response != null) {
                               handlerRayEyeCount(response.getOb().getCount());
                           }
                       }

                   });
    }

    /**
     * 在网络获取了了绑定信息后在这里处理
     *
     * @param bindVo
     * @param applicationCode
     */
    public static void handleBindInfo(HUDUtil mHUDUtil, final Activity activity, BindVo bindVo, final String applicationCode) {
        if (mHUDUtil == null || activity == null) {
            return;
        }
        if (Constants.CANT_USE.equals(bindVo.getStatus() + "")) {
            mHUDUtil.showDoneTip(R.string.city_cant_use);
        } else if (Constants.CAN_USE.equals(bindVo.getStatus()) || Constants.NO_SHENHE_CANUSE.equals(bindVo.getStatus())) {
            mHUDUtil.hidden();
            //这里是可以进去
            if (ApplicationInfo.ApplicationCode.HIDDEN_DANGER.getCode().equals(applicationCode)) {//
                UIHelper.showHiddenMainActivity(activity);
            } else if (ApplicationInfo.ApplicationCode.ANJIAN_NOTICE.getCode().equals(applicationCode)) {//通知公告
                CompanyInfo companyByBindVo = new CompanyInfo();
                companyByBindVo.setCompany_code(StringUtils.nullValue(bindVo.getBindCode()));
                companyByBindVo.setCompany_name(StringUtils.nullValue(bindVo.getBindName()));
                Bundle bundle = new Bundle();
                bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                UIHelper.showActivity(activity, bundle, NoticeListActivity.class);
            } else if (ApplicationInfo.ApplicationCode.FIRE_SAFE.getCode().equals(applicationCode)) {
                CompanyInfo companyByBindVo = new CompanyInfo();
                companyByBindVo.setCompany_code(StringUtils.nullValue(bindVo.getBindCode()));
                companyByBindVo.setCompany_name(StringUtils.nullValue(bindVo.getBindName()));
                if (UserTypeHelper.isSafer()) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                    UIHelper.showActivity(activity, bundle, SafeInspectionPanelActivity.class);

                } else if (UserTypeHelper.isWorker()) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                    UIHelper.showActivity(activity, bundle, PanelActivity.class);
                } else {
                    mHUDUtil.showErrorTip("角色功能开发中");
                }
            } else if (ApplicationInfo.ApplicationCode.FIRE_SUPERVISON.getCode().equals(applicationCode)) {//消防物联
               /* CompanyInfo companyByBindVo = new CompanyInfo();
                companyByBindVo.setCompany_code(StringUtils.nullValue(bindVo.getBindCode()));
                companyByBindVo.setCompany_name(StringUtils.nullValue(bindVo.getBindName()));
                Bundle bundle = new Bundle();
                bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                //UIHelper.showActivity(activity, bundle, BuildingListActivity.class);
                UIHelper.showActivity(activity, bundle, FirefightingMainActivity.class);*/
            }
        } else if (Constants.NO_SHENHE.equals(bindVo.getStatus())) {//审核中
            mHUDUtil.showDoneTip(R.string.bind_info_verify);
        } else if (Constants.NO_BIND.equals(bindVo.getStatus())) {//没有绑定处理
            mHUDUtil.hidden();
            if (bindVo == null) {
                bindVo = new BindVo();
            }
            int    newPermCode   = Convertor.toInt(StringUtils.nullValue(bindVo.getHasNewPerm(), "0"));
            String dialogContent = activity.getString(R.string.bind_info_confirm_bind);
            if (StringUtils.nullValue(bindVo.getApplicationRemark().trim()).length() != 0) {
                dialogContent = "<font color=black>" + dialogContent + "</font><br>" + StringUtils.nullValue(bindVo.getApplicationRemark());
            }
            switch (newPermCode) {
                case 0: {//不可以新建
                    new MaterialDialog.Builder(activity).title(R.string.tip_str_title)
                                                        .content("您不能使用该应用！")
                                                        .positiveText(R.string.sure_str)
                                                        .show();
                    break;
                }
                case 1: {//可以新建 可以选择
                    new MaterialDialog.Builder(activity).title(R.string.tip_str_title)
                                                        .content(Html.fromHtml(dialogContent))
                                                        .positiveText(R.string.sure_str)
                                                        .negativeText(R.string.cancel_str)
                                                        .onAny(new MaterialDialog.SingleButtonCallback() {
                                                            @Override
                                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                                if (which == DialogAction.POSITIVE) {
                                                                    if (UserTypeHelper.isGovUser()) {
                                                                        UIHelper.showGovBindInfo(activity, applicationCode, true);
                                                                    } else {
                                                                        UIHelper.showComBindInfo(activity, applicationCode, true);
                                                                    }
                                                                }
                                                            }
                                                        })
                                                        .show();

                    break;
                }
                case 2: {//只能选择限制的企业列表(只能选择）
                    new MaterialDialog.Builder(activity).title(R.string.tip_str_title)
                                                        .content(Html.fromHtml(dialogContent))
                                                        .positiveText(R.string.sure_str)
                                                        .negativeText(R.string.cancel_str)
                                                        .onAny(new MaterialDialog.SingleButtonCallback() {
                                                            @Override
                                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                                if (which == DialogAction.POSITIVE) {
                                                                    if (UserTypeHelper.isGovUser()) {
                                                                        UIHelper.showGovBindInfo(activity, applicationCode, false);
                                                                    } else {
                                                                        UIHelper.showComBindInfo(activity, applicationCode, false);
                                                                    }
                                                                }
                                                            }
                                                        })
                                                        .show();
                    break;
                }
                default:
                    break;
            }
        }
    }


    /**
     * 获取消防物联权限
     * @param bindVo
     */
    private void httpGetFireBind(final BindVo bindVo, final String applicationCode){

        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("application_code", "fire_supervision");

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Gov_bind), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    OldBaseMode baseMode = JsonUtils.fromJson(result, OldBaseMode.class);
                    Bundle bundle;
                    CompanyInfo companyByBindVo;
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (!baseMode.isIsError()) {
                            try {
                                Gson mGson=new Gson();
                                FireGovBindMode fireGovBindMode = mGson.fromJson(mGson.toJson(baseMode.getResult()), FireGovBindMode.class);
                                switch (fireGovBindMode.getStatus()){
                                    case "-1":
                                        mHUDUtil.showDoneTip("所在城市或角色不能使用该应用");
                                        break;
                                    case "0":
                                        companyByBindVo = new CompanyInfo();
                                        companyByBindVo.setCompany_code(StringUtils.nullValue(fireGovBindMode.getBindCode()));
                                        companyByBindVo.setCompany_name(StringUtils.nullValue(fireGovBindMode.getBindName()));
                                        bundle = new Bundle();
                                        bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                                        //UIHelper.showActivity(activity, bundle, BuildingListActivity.class);
                                        UIHelper.showActivity(getActivity(), bundle, FirefightingMainActivity.class);
                                        break;
                                    case "1":
                                        mHUDUtil.showDoneTip(fireGovBindMode.getBindName()+"请等待审核");
                                        break;
                                    case "2":
                                        //mHUDUtil.showDoneTip("未绑定");
                                        fireBind(bindVo,applicationCode);
                                        break;
                                    case "3":
                                        companyByBindVo = new CompanyInfo();
                                        companyByBindVo.setCompany_code(StringUtils.nullValue(fireGovBindMode.getBindCode()));
                                        companyByBindVo.setCompany_name(StringUtils.nullValue(fireGovBindMode.getBindName()));
                                        bundle = new Bundle();
                                        bundle.putSerializable(BundleKey.COMPANY_INFO, companyByBindVo);
                                        //UIHelper.showActivity(activity, bundle, BuildingListActivity.class);
                                        UIHelper.showActivity(getActivity(), bundle, FirefightingMainActivity.class);
                                        break;
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            mHUDUtil.showErrorTip(baseMode.getError().getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     *    绑定机构
     *
     * @param bindVo
     * @param applicationCode
     */
    private void fireBind( BindVo bindVo, final String applicationCode){
        mHUDUtil.hidden();
        if (bindVo == null) {
            bindVo = new BindVo();
        }
        int    newPermCode   = Convertor.toInt(StringUtils.nullValue(bindVo.getHasNewPerm(), "0"));
        String dialogContent = getActivity().getString(R.string.bind_info_confirm_bind);
        if (StringUtils.nullValue(bindVo.getApplicationRemark().trim()).length() != 0) {
            dialogContent = "<font color=black>" + dialogContent + "</font><br>" + StringUtils.nullValue(bindVo.getApplicationRemark());
        }
        switch (newPermCode) {
            case 0: {//不可以新建
                new MaterialDialog.Builder(getActivity()).title(R.string.tip_str_title)
                        .content("您不能使用该应用！")
                        .positiveText(R.string.sure_str)
                        .show();
                break;
            }
            case 1: {//可以新建 可以选择
                new MaterialDialog.Builder(getActivity()).title(R.string.tip_str_title)
                        .content(Html.fromHtml(dialogContent))
                        .positiveText(R.string.sure_str)
                        .negativeText(R.string.cancel_str)
                        .onAny(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                if (which == DialogAction.POSITIVE) {
                                    if (UserTypeHelper.isGovUser()) {
                                        UIHelper.showGovBindInfo(getActivity(), applicationCode, true);
                                    } else {
                                        UIHelper.showComBindInfo(getActivity(), applicationCode, true);
                                    }
                                }
                            }
                        })
                        .show();
                break;
            }
            case 2: {//只能选择限制的企业列表(只能选择）
                new MaterialDialog.Builder(getActivity()).title(R.string.tip_str_title)
                        .content(Html.fromHtml(dialogContent))
                        .positiveText(R.string.sure_str)
                        .negativeText(R.string.cancel_str)
                        .onAny(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                if (which == DialogAction.POSITIVE) {
                                    if (UserTypeHelper.isGovUser()) {
                                        UIHelper.showGovBindInfo(getActivity(), applicationCode, false);
                                    } else {
                                        UIHelper.showComBindInfo(getActivity(), applicationCode, false);
                                    }
                                }
                            }
                        })
                        .show();
                break;
            }
            default:
                break;
        }
    }





}
